clc,clear;
close all;
warning off;
%% 导入数据
res=readmatrix('工作簿2.xlsx');
res1=res(383:end,7:9);
res=res(1:382,[7:9,12]);

%% 数据归一化 索引
X=res(:,1:end-1);
Y=res(:,end);
[x,psin]=mapminmax(X',0,1);

%% 划分训练集与测试集
num=size(res,1); %总样本数
k=1;

%是否打乱样本
if k==0
    state=1:num;
else
    state=randperm(num);
end

r=0.9;  %训练集占比
trainnum=floor(num*r);
testnum=num-trainnum;

xtrain=x(:,state(1:trainnum))';
ytrain=Y(state(1:trainnum));

xtext=x(:,state(trainnum+1:end))';
ytext=Y(state(trainnum+1:end));

%% 构建svm多分类模型
%创建一个SVM模版,设置参数
t=templateSVM('Standardize',true,'KernelFunction','rbf','Solver','SMO','IterationLimit',10e9,'KernelScale','auto','BoxConstraint',1,'boxConstraint',1);
Mdl=fitcecoc(xtrain,ytrain,'Learners',t);

%% 仿真测试
re1=predict(Mdl,xtrain);
re2=predict(Mdl,xtext);
kinds=numel(unique(ytrain));
% roc曲线
%% 按编号从小到大排序,方便查看
[ytrain,id1]=sort(ytrain);
[ytext,id2]=sort(ytext);

re1=re1(id1);
re2=re2(id2);

%% 性能评价
plk1=sum((re1==ytrain))/trainnum*100;
plk2=sum((re2==ytext))/testnum*100;

%% 绘图
figure
subplot(1,2,1)
plot(ytrain,'-*','LineWidth',1,Color=[68,117,122]./255)
hold on
plot(re1,'-o','LineWidth',1,Color=[212,76,60]./255)
legend('实际类','预测类')
xlabel('样本')
ylabel('类别')
title(['训练集预测准确率为：',num2str(plk1),'%'])
yticks(1:kinds)
yticklabels(1:kinds)
grid

figure
subplot(1,2,1)
plot(ytext,'-*','LineWidth',1,Color=[68,117,122]./255)
hold on
plot(re2,'-o','LineWidth',1,Color=[212,76,60]./255)
legend('实际类','预测类')
xlabel('样本')
ylabel('类别')
title(['测试集预测准确率为：',num2str(plk2),'%'])
yticks(1:kinds)
yticklabels(1:kinds)
grid

%% 混淆矩阵
figure
subplot(1,2,1)
cm=confusionchart(ytrain,re1);
cm.Title='训练集混淆矩阵';
cm.ColumnSummary='column-normalized';
cm.RowSummary='row-normalized';

figure
subplot(1,2,1)
cm=confusionchart(ytext,re2);
cm.Title='测试集混淆矩阵';
cm.ColumnSummary='column-normalized';
cm.RowSummary='row-normalized';

%% 预测
newdata=res1;%预测的数据
newy=newpre(newdata,psin,Mdl);
%保存数据
% xlswrite('coordinates.xlsx',newy)


function y=newpre(newdata,psin,Mdl)
    %归一化
    x=mapminmax('apply',newdata',psin);
    %预测
    y=predict(Mdl,x');
end